<template>
  <div class="p-[20px]">
    <div class="item">
      <div class="label">图片内容</div>
      <div class="mt-[10px] val">
        <div class="flex cursor-pointer h-[140px] justify-center items-center flex-col relative rounded-[4px] addbox">
          <div class="absolute top-0 left-0 upload">
            <el-upload
              ref="imageUpload"
              :action="uploadImgUrl"
              list-type="picture-card"
              :on-success="handleUploadSuccess"
              :before-upload="handleBeforeUpload"
              :on-error="handleUploadError"
              :before-remove="handleDelete"
              :show-file-list="true"
              :headers="headers"
            >
              <el-icon class="avatar-uploader-icon">
                <plus />
              </el-icon>
            </el-upload>
          </div>
          <div class="flex justify-center items-center flex-col">
            <div class="icon">
              <el-icon><Plus /></el-icon>
            </div>
            <div class="text-[12px] text">添加图片</div>
          </div>
        </div>
        <div class="imagebox"></div>
      </div>
    </div>

    <el-dialog v-model="open" :title="title" width="800px" append-to-body>
      <el-row>
        <el-col :xs="24" :md="12" :style="{ height: '350px' }">
          <vue-cropper
            v-if="visible"
            ref="cropper"
            :img="options.img"
            :info="true"
            :auto-crop="options.autoCrop"
            :auto-crop-width="options.autoCropWidth"
            :auto-crop-height="options.autoCropHeight"
            :fixed-box="options.fixedBox"
            :output-type="options.outputType"
            @real-time="realTime"
          />
        </el-col>
        <el-col :xs="24" :md="12" :style="{ height: '350px' }">
          <div class="avatar-upload-preview">
            <img :src="options.previews.url" :style="options.previews.img" />
          </div>
        </el-col>
      </el-row>
      <br />
      <el-row>
        <el-col :lg="2" :md="2">
          <el-upload action="#" :http-request="requestUpload" :show-file-list="false" :before-upload="beforeUpload">
            <el-button>
              选择
              <el-icon class="el-icon--right">
                <Upload />
              </el-icon>
            </el-button>
          </el-upload>
        </el-col>
      </el-row>
    </el-dialog>
    <div class="absolute opacity-0 z--1 upload"></div>
  </div>
</template>

<script setup lang="ts">
import 'vue-cropper/dist/index.css';
import { VueCropper } from 'vue-cropper';
import { uploadAvatar } from '@/api/system/user';
import useUserStore from '@/store/modules/user';
import { UploadRawFile } from 'element-plus';
import { globalHeaders } from '@/utils/request';
import { listByIds, delOss } from '@/api/system/oss';
import { compressAccurately } from 'image-conversion';

const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadImgUrl = ref(baseUrl + 'resource/oss/upload'); // 上传的图片服务器地址
const headers = ref(globalHeaders());

const fileList = ref<any[]>([]);
const uploadList = ref<any[]>([]);
const fileType = ref(['png', 'jpg', 'jpeg']);
const fileSize = ref(5);
const compressTargetSize = ref(300);
const compressSupport = ref(false);

interface Options {
  img: string | any; // 裁剪图片的地址
  autoCrop: boolean; // 是否默认生成截图框
  autoCropWidth: number; // 默认生成截图框宽度
  autoCropHeight: number; // 默认生成截图框高度
  fixedBox: boolean; // 固定截图框大小 不允许改变
  fileName: string;
  previews: any; // 预览数据
  outputType: string;
  visible: boolean;
}

const imageUrl = ref();
const imageUploadRef = ref();

const userStore = useUserStore();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const open = ref(false);
const visible = ref(false);
const title = ref('裁剪图片');

const cropper = ref<any>({});
//图片裁剪数据
const options = reactive<Options>({
  img: userStore.avatar,
  autoCrop: true,
  autoCropWidth: 200,
  autoCropHeight: 200,
  fixedBox: true,
  outputType: 'png',
  fileName: '',
  previews: {},
  visible: false
});

/** 编辑头像 */
const editCropper = () => {
  open.value = true;
  visible.value = true;
};

/** 覆盖默认上传行为 */
const requestUpload = (): any => {};

/** 实时预览 */
const realTime = (data: any) => {
  options.previews = data;
};
/** 上传预处理 */
const beforeUpload = (file: UploadRawFile): any => {
  console.log('file', file);
  if (file.type.indexOf('image/') == -1) {
    proxy?.$modal.msgError('文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。');
  } else {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      options.img = reader.result;
      options.fileName = file.name;
      console.log('options', options);
    };
  }
};
/** 上传图片 */
const uploadImg = async () => {
  cropper.value.getCropBlob(async (data: any) => {
    let formData = new FormData();
    formData.append('avatarfile', data, options.fileName);
    const res = await uploadAvatar(formData);
    open.value = false;
    options.img = res.data.imgUrl;
    userStore.setAvatar(options.img);
    proxy?.$modal.msgSuccess('修改成功');
    visible.value = false;
  });
};

/** 上传前loading加载 */
const handleBeforeUpload = (file: any) => {
  let isImg = false;
  if (fileType.value.length) {
    let fileExtension = '';
    if (file.name.lastIndexOf('.') > -1) {
      fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1);
    }
    isImg = fileType.value.some((type: any) => {
      if (file.type.indexOf(type) > -1) return true;
      if (fileExtension && fileExtension.indexOf(type) > -1) return true;
      return false;
    });
  } else {
    isImg = file.type.indexOf('image') > -1;
  }
  if (!isImg) {
    proxy?.$modal.msgError(`文件格式不正确, 请上传${fileType.value.join('/')}图片格式文件!`);
    return false;
  }
  if (file.name.includes(',')) {
    proxy?.$modal.msgError('文件名不正确，不能包含英文逗号!');
    return false;
  }
  if (fileSize.value) {
    const isLt = file.size / 1024 / 1024 < fileSize.value;
    if (!isLt) {
      proxy?.$modal.msgError(`上传头像图片大小不能超过 ${fileSize.value} MB!`);
      return false;
    }
  }

  //压缩图片，开启压缩并且大于指定的压缩大小时才压缩
  if (compressSupport.value && file.size / 1024 > compressTargetSize.value) {
    // proxy?.$modal.loading('正在上传图片，请稍候...');
    return compressAccurately(file, compressTargetSize.value);
  } else {
    // proxy?.$modal.loading('正在上传图片，请稍候...');
  }
};

// 上传成功回调
const handleUploadSuccess = (res: any, file: UploadFile) => {
  if (res.code === 200) {
    uploadList.value.push({ name: res.data.fileName, url: res.data.url, ossId: res.data.ossId });
    uploadedSuccessfully();
  } else {
    proxy?.$modal.closeLoading();
    proxy?.$modal.msgError(res.msg);
    imageUploadRef.value?.handleRemove(file);
    uploadedSuccessfully();
  }
};
// 上传结束处理
const uploadedSuccessfully = () => {
  fileList.value = fileList.value.filter((f) => f.url !== undefined).concat(uploadList.value);
  uploadList.value = [];
  // emit('update:modelValue', listToString(fileList.value));
  imageUrl.value = listToString(fileList.value);
  proxy?.$modal.closeLoading();
};

// 上传失败
const handleUploadError = () => {
  proxy?.$modal.msgError('上传图片失败');
  proxy?.$modal.closeLoading();
};

// 删除图片
const handleDelete = (file: UploadFile): boolean => {
  const findex = fileList.value.map((f) => f.name).indexOf(file.name);
  if (findex > -1) {
    let ossId = fileList.value[findex].ossId;
    delOss(ossId);
    fileList.value.splice(findex, 1);
    return false;
  }
  return true;
};
// 对象转成指定字符串分隔
const listToString = (list: any[], separator?: string) => {
  let strs = '';
  separator = separator || ',';
  for (let i in list) {
    if (undefined !== list[i].ossId && list[i].url.indexOf('blob:') !== 0) {
      strs += list[i].ossId + separator;
    }
  }
  return strs != '' ? strs.substring(0, strs.length - 1) : '';
};

const addImage = () => {
  imageUploadRef.value?.$el.click();
};
</script>

<style lang="scss" scoped>
.addbox {
  border: 1px dashed #ccc;
  color: #ccc;
  &:hover {
    border: 1px dashed #4d8fff;
    color: #4d8fff;
  }
}
::v-deep(.el-upload--picture-card) {
  width: 360px !important;
  opacity: 0 !important;
}
::v-deep(.el-upload-list) {
  opacity: 0 !important;
}
</style>
